<template>
  <div class="">
    <div class="cardHeader">
      <img class="cardHeader_icon m_hoverCP" src="@assets/img/img28.png" alt="" @click="onBack"/>
      <span class="m_hoverCP" @click="onBack">{{$t('message.Add_carbon_emission_factor')}}</span>
    </div>
    <section class="cardBox">
      <div class="cardBox_title">{{$t('message.Carbon_emission_factor_information')}}</div>
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Factor_name')" required>
                <a-input v-model="queryParam.name" allowClear :placeholder="$t('message.Please_enter')" :maxLength="32"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Database')" required>
                <a-select v-model="queryParam.type" disabled>
                  <a-select-option value="1"> {{$t('message.Carbon_emission_factor_library')}}</a-select-option>
                  <a-select-option value="2"> {{$t('message.Tissue_factor_library')}}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Specifications_and_models')">
                <a-input v-model="queryParam.model" allowClear :placeholder="$t('message.Please_enter')" :maxLength="32"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Applicable_industries')">
                <a-select v-model="queryParam.industryId" allowClear :placeholder="$t('message.Please_select')" show-search
                          :filter-option="filterOption" @change="onChangeIndustryId">
                  <a-select-option :value="item.id" v-for="(item,index) in industryData" :key="index">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Product_classification')">
                <a-select v-model="queryParam.productClassification" allowClear :placeholder="$t('message.Please_select')" show-search
                          :filter-option="filterOption">
                  <a-select-option :value="item.value" v-for="(item,index) in product_typeData" :key="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Applicable_scenario')">
                <a-input v-model="queryParam.scene" allowClear :placeholder="$t('message.Please_enter')" :maxLength="256"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Factor_description')">
                <a-input v-model="queryParam.instruction" allowClear :placeholder="$t('message.Please_enter')" :maxLength="512"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </section>
    <section class="cardBox" style="">
      <div class="cardBox_title">{{$t('message.Data_details')}}</div>
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Factor_unit')" required>
                <div class="m_cFlex">
                  <a-select v-model="queryParam.numeratorUnitId" :placeholder="$t('message.Please_select')" show-search
                            :filter-option="filterOption" @change="onChangeNumeratorUnitId">
                    <a-select-option :value="item.id" v-for="(item,index) in fzData" :key="index">
                      {{ item.factorUnit }}
                    </a-select-option>
                  </a-select>
                  <span style="margin: 0 10px;">/</span>
                  <a-select v-model="queryParam.denominatorUnitId" :placeholder="$t('message.Please_select')" show-search
                            :filter-option="filterOption" @change="onChangeDenominatorUnitId">
                    <a-select-option :value="item.id" v-for="(item,index) in fmData" :key="index">
                      {{ item.unitCode }}
                    </a-select-option>
                  </a-select>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item ::label="`${$t('message.Factor_value')}（${$t('message.Carbon_dioxide_equivalent')}）`" required>
                <div class="m_cFlex">
                  <a-input-number v-model="queryParam.factorValue" :step="0.0001" :precision="4"
                                  :disabled="queryParam.computerType == 2" allowClear :placeholder="$t('message.Please_enter')"
                                  style="width: 200px"/>
                  <div class="switchBtn m_hoverCP" @click="onChangeComputerType "
                       v-if="queryParam.computerType == 1">
                    <img class="switchBtn_icon " src="@assets/img/img29.png" alt=""/>{{$t('message.Switch_ratio_calculation')}}
                  </div>
                  <div class="switchBtn m_hoverCP" @click="queryParam.computerType = 1"
                       v-if="queryParam.computerType == 2">
                    <img class="switchBtn_icon " src="@assets/img/img29.png" alt=""/>{{$t('message.Switch_manual_transmission')}}
                  </div>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <div style="margin-top: 20px;width: 1300px;" v-if="queryParam.computerType == 2">
        <a-table :columns="columns" :dataSource="queryParam.gasList" :pagination="false" :bordered="false"
                 size="middle">
          <template slot="gasName" slot-scope="text, record">
            <a-select v-model="record.gasName" :placeholder="$t('message.Please_select')" show-search :filter-option="filterOption"
                      @change="onChangeGas($event,record)" style="width: 100%;">
              <a-select-option :value="item.gasName" :disabled="item.disabled" v-for="(item,index) in gasData"
                               :key="item.gasName">
                {{ item.gasName }}
              </a-select-option>
            </a-select>
          </template>
          <template slot="factorValue" slot-scope="text, record">
            <a-input-number v-model="record.factorValue" :step="0.0001" :precision="4" :placeholder="$t('message.Please_enter')"
                            @change="computeFactorValue" style="width: 100%;"/>
          </template>
          <template slot="gwpValue" slot-scope="text, record">
            <a-input-number v-model="record.gwpValue" :step="0.01" :precision="4" :placeholder="$t('message.Please_enter')"
                            @change="computeFactorValue" style="width: 100%;"/>
          </template>
          <div class="m_ccFlex" slot="action" slot-scope="text, record, index">
            <a-popconfirm :title="$t('message.Confirm_delete')" :cancelText="$t('message.Cancel')"
                  :okText="$t('message.Confirm')" @confirm="() => onDel(index)">
              <a>{{$t('message.Delete')}}</a>
            </a-popconfirm>
          </div>
        </a-table>
        <div class="addBtn m_hoverCP" @click="onAdd">
          <img class="addBtn_icon " src="@assets/img/img30.png" alt=""/>{{$t('message.Add_gas')}}
        </div>
      </div>
    </section>
    <section class="cardBox" :style="{'paddingBottom':paddingBottom}">
      <div class="cardBox_title">{{$t('message.Source_information')}}</div>
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Release_organization')">
                <a-input v-model="queryParam.releaseOrg" allowClear :placeholder="$t('message.Please_enter')" :maxLength="64"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Release_year')">
                <a-select v-model="queryParam.releaseYear" allowClear :placeholder="$t('message.Please_select')" show-search
                          :filter-option="filterOption">
                  <a-select-option :value="item" v-for="(item,index) in yearData" :key="item">
                    {{ item }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Source_type')">
                <a-select v-model="queryParam.sourceType" allowClear :placeholder="$t('message.Please_select')" show-search
                          :filter-option="filterOption">
                  <a-select-option :value="item.value" v-for="(item,index) in source_typeData" :key="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Document_type')">
                <a-select v-model="queryParam.docType" allowClear :placeholder="$t('message.Please_select')" show-search
                          :filter-option="filterOption">
                  <a-select-option :value="item.value" v-for="(item,index) in document_typeData" :key="item.value">
                    {{ item.text }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Country_organization')">
                <a-input v-model="queryParam.ownership" allowClear :placeholder="$t('message.Please_enter')" :maxLength="128"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Source_file')">
                <a-input v-model="queryParam.sourceFile" allowClear :placeholder="$t('message.Please_enter')" :maxLength="128"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Source_URL_link')">
                <a-input v-model="queryParam.sourceUrlLink" allowClear :placeholder="$t('message.Please_enter')" :maxLength="128"></a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-model-item :label="$t('message.Attachment')">
                <j-upload v-model="queryParam.attachments" :number="3"></j-upload>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </section>
    <div class="optionBox">
      <div class="optionItem optionItem_cancel m_hoverCP" @click="onBack"> {{$t('message.Cancel')}}</div>
      <div class="optionItem optionItem_confirm m_hoverCP" @click="onSubmit"> {{$t('message.Confirm')}}</div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import {ACCESS_TOKEN} from "@/store/mutation-types";
import {getAction, postAction} from "@api/manage";
import {INDUSTRY} from "@/common/constKey";
// import {cloneObject} from '@/utils/util'

export default {
  name: 'tpyzForm',
  components: {},
  data() {
    return {
      columns: [{
        title: this.$t('message.greenhouse_gas'),
        align: 'center',
        dataIndex: 'gasName',
        width: 150,
        scopedSlots: {customRender: 'gasName'},
      }, {
        title: this.$t('message.Factor_value'),
        align: 'center',
        dataIndex: 'factorValue',
        width: 100,
        scopedSlots: {customRender: 'factorValue'},
      }, {
        title: this.$t('message.Factor_molecular_unit'),
        align: 'center',
        dataIndex: 'molecularUnit',
        width: 100,
      }, {
        title: this.$t('message.Factor_denominator_unit'),
        align: 'center',
        dataIndex: 'denominatorUnit',
        width: 100,
      }, {
        title: this.$t('message.GWP_value'),
        align: 'center',
        dataIndex: 'gwpValue',
        width: 100,
        scopedSlots: {customRender: 'gwpValue'},
      }, {
        title: this.$t('message.Handle'),
        align: 'center',
        width: 100,
        scopedSlots: {customRender: 'action'},
      }],
      queryParam: {
        gasList: [],
        computerType: 1, // 类型（1=手动输入，2=配比计算）
        type: '2', // 数据库,默认组织因子库,不可更改（1=碳排因子库，2=组织因子库）
      },
      fzData: [],// 因子分子数据
      fmData: [],// 因子分母数据
      yearData: [],// 因子分母数据
      gasData: [],// 气体数据
      industryData: [], // 行业数据
      source_typeData: [], // 来源类型
      product_typeData: [], // 因子分类
      document_typeData: [], // 文献类型
      allGasData: [], // 气体二位数组数据
    };
  },
  computed: {
    paddingBottom() {
      if (this.queryParam.attachments) {
        return this.queryParam.attachments.split(',').length * 25 + 12 + 'px'
      } else {
        return '12px'
      }
    }
  },
  watch: {
    'queryParam.gasList': {
      deep: true,
      handler(val, oldVal) {
        // console.log('watch =>', val, oldVal)
        let keyData = []
        val.forEach(item => {
          if (item.gasName) {
            keyData.push(item.gasName)
          }
        })
        // console.log('watch keyData =>', keyData)
        this.gasData.forEach(item => {
          if (keyData.includes(item.gasName)) {
            this.$set(item, 'disabled', true)
          } else {
            this.$set(item, 'disabled', false)
          }
        })
        // console.log('watch gasData =>', this.gasData)
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    onChangeIndustryId(e) {
      console.log('onChangeIndustryId', e)
      let theIndex = this.industryData.findIndex(ele => ele.id == e)
      if (theIndex > -1) {
        this.queryParam.industry = this.industryData[theIndex].name
      }
    },
    /**
     * 配比计算-根据气体计算因子值
     */
    computeFactorValue() {
      let data = 0
      this.queryParam.gasList.forEach(item => {
        let factorValue = item.factorValue ? Number(item.factorValue) : 0
        let gwpValue = item.gwpValue ? Number(item.gwpValue) : 0
        data = data + (factorValue * gwpValue)
      })
      this.$set(this.queryParam, 'factorValue', Number((data).toFixed(4)))
    },
    onChangeComputerType() {
      if (this.queryParam.computerType == 1) {
        // 从手动切换到配比计算
        this.queryParam.computerType = 2
        this.onChangeNumeratorUnitId(this.queryParam.numeratorUnitId)
      } else if (this.queryParam.computerType == 2) {
        // 从配比计算切换到手动
        this.queryParam.computerType = 1
      }
      this.queryParam.gasList = []
      this.computeFactorValue()
    },
    /**
     * 修改分子单位，同时删除温室气体
     */
    onChangeNumeratorUnitId(value) {
      console.log('onChangeNumeratorUnitId', value)
      let theIndex = this.fzData.findIndex(ele => ele.id == value)
      if (theIndex > -1) {
        this.$set(this.queryParam, 'numeratorUnit', this.fzData[theIndex].factorUnit)
        this.gasData = this.allGasData[theIndex]
        if (this.queryParam.gasList && this.queryParam.gasList.length > 0) {
          this.queryParam.gasList.forEach((gasItem, gasIndex) => {
            this.gasData.forEach((gasItem2, gasIndex2) => {
              if (gasItem.gasName === gasItem2.gasName) {
                console.log('gasItem2', gasItem2)
                gasItem.molecularUnit = gasItem2.gasUnit
              }
            })
          })
        }
        this.computeFactorValue()
      }
    },
    /**
     * 修改分母单位，同时修改所有温室气体的因子分母单位
     */
    onChangeDenominatorUnitId(value) {
      console.log('onChangeDenominatorUnitId', value)
      let theIndex = this.fmData.findIndex(ele => ele.id == value)
      if (theIndex > -1) {
        this.$set(this.queryParam, 'denominatorUnit', this.fmData[theIndex].unitCode)
        this.queryParam.gasList.forEach(item => {
          this.$set(item, 'denominatorUnit', this.fmData[theIndex].unitCode)
        })
      }
    },
    /**
     * 添加气体
     */
    onAdd() {
      console.log('onAdd');
      let obj = {}
      if (this.queryParam.denominatorUnitId) {
        obj.denominatorUnit = this.queryParam.denominatorUnit
      }
      this.queryParam.gasList.push(obj)
    },
    /**
     * 删除气体
     */
    onDel(index) {
      console.log('onAdd');
      this.queryParam.gasList.splice(index, 1)
      this.computeFactorValue()
    },
    /**
     * 修改气体
     * @param e
     * @param record
     */
    onChangeGas(e, record) {
      console.log('onChangeGas', e, record)
      let theIndex = this.gasData.findIndex(ele => ele.gasName == e)
      if (theIndex > -1) {
        this.$set(record, 'molecularUnit', this.gasData[theIndex].gasUnit)
        this.$set(record, 'gwpValue', this.gasData[theIndex].gwpValue)
        this.computeFactorValue()
      }
    },
    /**
     * 检查表单数据
     */
    checkFormData() {
      if (!this.queryParam.name) {
        this.$message.warn(this.$t('message.please_enter_factor_name'))
        return false
      }
      if (!this.queryParam.numeratorUnitId) {
        this.$message.warn(this.$t('message.please_select_the_factor_molecular_unit'))
        return false
      }
      if (!this.queryParam.denominatorUnitId) {
        this.$message.warn(this.$t('message.please_select_factor_denominator_unit'))
        return false
      }
      if (this.queryParam.computerType == 1) {
        // 手动输入
        if (!this.queryParam.factorValue || this.queryParam.factorValue && this.queryParam.factorValue < 0) {
          this.$message.warn(this.$t('message.please_enter_a_factor_value_co2_equivalent_greater_than_0'))
          return false
        }
      }
      if (this.queryParam.computerType == 2) {
        // 手动输入
        if (!this.queryParam.gasList || this.queryParam.gasList && this.queryParam.gasList.length == 0) {
          this.$message.warn(this.$t('message.please_add_at_least_one_gas'))
          return false
        }
        let errorIndex = null
        let errorType = null
        for (let i = 0; i < this.queryParam.gasList.length; i++) {
          let theObj = this.queryParam.gasList[i]
          if (!theObj.gasName) {
            errorIndex = i
            errorType = 'gasName'
            break
          }
          if (!theObj.factorValue || theObj.factorValue && theObj.factorValue < 0) {
            errorIndex = i
            errorType = 'factorValue'
            break
          }
          if (!theObj.gwpValue) {
            errorIndex = i
            errorType = 'gwpValue'
            break
          }
        }
        if (errorType === 'gasName') {
          this.$message.warn(this.$t('message.please_select_gas'))
          return false
        }
        if (errorType === 'factorValue') {
          this.$message.warn(this.$t('message.please_enter_a_factor_value_greater_than_0'))
          return false
        }
        if (errorType === 'gwpValue') {
          this.$message.warn(this.$t('message.please_enter_gwp_value'))
          return false
        }
      }
      return true
    },
    /**
     * 提交
     */
    onSubmit() {
      console.log('queryParam', this.queryParam)
      if (this.checkFormData()) {
        postAction('/emission/factor/cyEmissionFactor/add', this.queryParam).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('message.operation_success'))
            this.onBack()
          }
        });
      }
    },
    getData() {
      // 来源类型
      getAction('/sys/api/getDictItems', {
        dictCode: 'source_type'
      }).then((res) => {
        this.source_typeData = res || []
        console.log('getDictItems source_type =>', res)
      });
      // 因子分类
      getAction('/sys/api/getDictItems', {
        dictCode: 'product_type'
      }).then((res) => {
        this.product_typeData = res || []
        console.log('getDictItems product_type =>', res)
      });
      // 文献类型
      getAction('/sys/api/getDictItems', {
        dictCode: 'document_type'
      }).then((res) => {
        this.document_typeData = res || []
        console.log('getDictItems document_type =>', res)
      });
      // 行业
      getAction('/sys/category/childList', {
        pid: INDUSTRY
      }).then((res) => {
        if (res.success) {
          this.industryData = res.result || []
        }
      });
      // 分子
      getAction('/CyFactorUnit/cyFactorUnit/list').then((res) => {
        if (res.success) {
          this.fzData = res.result.records || []
          this.allGasData = []
          this.fzData.forEach((item, index) => {
            getAction('/gas/cyGasStore/listGasName', {
              factorRealUnit: item.factorRealUnit
            }).then((res) => {
              if (res.success) {
                this.allGasData[index] = res.result || []
              }
            });
          })
        }
      });
      // 分母
      getAction('/emission/factor/cyEmissionUnit/getAllUnit').then((res) => {
        if (res.success) {
          this.fmData = res.result || []
        }
      });
      // 年份
      let yearData = []
      for (let i = 1950; i < 2100; i++) {
        yearData.push(String(i))
      }
      this.yearData = yearData
    },
    // ==============================================================================
    /**
     * 下拉框数据过滤
     */
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    /**
     * 返回
     */
    onBack() {
      this.$emit('back')
    },
  },
};

</script>

<style lang="less" scoped>
.cardHeader {
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #000000;

  .cardHeader_icon {
    width: 16px;
    height: 16px;
  }
}

.cardBox {
  margin-top: 24px;
  overflow: hidden;
  padding: 32px 24px 12px;
  background: #FFFFFF;
  border-radius: 3px;

  .cardBox_title {
    margin-bottom: 24px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 20px;
    color: #333333;
  }
}

.switchBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-left: 8px;
  padding: 0 16px;
  // width: 140px;
  height: 32px;
  background: #FFFFFF;
  border-radius: 3px;
  border: 1px solid #148958;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #148958;
  white-space: nowrap;

  .switchBtn_icon {
    width: 16px;
    height: 16px;
  }
}

.addBtn {
  margin-top: 16px;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 112px;
  height: 32px;
  background: #FFFFFF;
  border-radius: 3px;
  border: 1px solid #148958;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 14px;
  color: #148958;

  .addBtn_icon {
    width: 16px;
    height: 16px;
  }
}

.optionBox {
  margin-top: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24px;

  .optionItem {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 103px;
    height: 32px;
    border-radius: 3px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
  }

  .optionItem_cancel {
    background: #E7E7E7;
    color: rgba(0, 0, 0, 0.9);
  }

  .optionItem_confirm {
    background: #148958;
    color: rgba(255, 255, 255, 0.9);
  }
}
</style>
